<!--这是上传音频组件-->
<template>
	<div style="padding-bottom: 30px;">
		<div class="addBox">
			<h3><span>上传音频</span></h3>
			<div style="margin: 0 20px;">
				<p style="line-height: 36px;">已上传列表：</p>
				<table v-loading="loading">
					<tr>
						<th>音频名称</th>
						<!-- <th>老师名称</th> -->
						<!-- <th>是否已转码成AAC格式</th> -->
            <th>是否已切片</th>
						<th>操作</th>
					</tr>
					<tr v-for="(item,index) in audioList" :key="index">
						<td>{{ item.audioName }}</td>
						<!-- <td>{{uploadData.lecturerName }}</td> -->
						<!-- <td>{{uploadData.qiniuId }}</td> -->
            <td>{{ item.audioM3u8 ? '是' : '否' }}</td>
						<td>
              <b v-show="!item.audioM3u8" @click="handleSlice(item.courseDetailId)">点击切片</b>
              &nbsp;&nbsp;&nbsp;
              <b @click="deleteDatum(item.courseDetailId,index)">删除</b>
            </td>
					</tr>
				</table>
        <code>
          <svg-icon icon-class="message" style="margin-right:10px;color:red;font-size:20px;"></svg-icon>
          操作说明：<br>
          若发现音频加载缓慢，可点击操作栏进行切片。<br>
          1.切片前需要先将音频转成AAC文件格式，此过程受文件大小，网速等物理因素影响，需要静候20-40秒，请静候一段时间刷新页面，查看转码状态。<br>
          2.切片前先刷新页面，确保该音频已经为ACC格式，切片过程受文件大小，网速等物理因素影响，需要静候1-5分钟，请静候一段时间刷新页面，查看转码状态。<br>
          3.请严格按照指示说明操作。（此操作建议有需要再转码）
        </code>
        <code>
          <svg-icon icon-class="message" style="margin-right:10px;color:red;font-size:20px;"></svg-icon>
          提示：
          音频格式只支持MP3格式
        </code>
        <el-upload
          class="upload-demo"
          name="file"
          action="https://upload-z2.qiniup.com"
          :on-preview="handlePreview"
          :on-success="handleSuccess"
          :before-upload="beforeAvatarUpload"
          :on-error="handleError"
          :file-list="fileList"
          :data="formData"
          :disabled="btnLoading"
          list-type="picture">
          <el-button size="small" type="primary" v-loading="btnLoading">选取音频文件</el-button>
          <div slot="tip" class="el-upload__tip"></div>
        </el-upload>
			</div>
      </div>
    </div>
  </template>
<script>
  import { getUploadToken } from '@/api/qiniu'
  import { saveAudioDetail, getAudioList, audioSlice ,delAudio} from '@/api/courseDetail'

  const postForm = {
    audioName: null,
    qiniuObject: null
  }

  const uploadData = {
    audioName: null,
    audioM3u8: null
  }

  export default {
    data() {
      return {
        postForm,
        uploadData,
        formData: {
          token: null
          // key: null
        },
        fileName: null,
        fileList:[],
        audioList:[],
        btnLoading: false,
        loading:false,
        courseId: null
      }
    },
    created() {
      this.getToken()
      this.initData()
    },
    methods: {
      getToken() {
        getUploadToken().then(res => {
          this.formData.token = res.data.data
        }).catch(err => {
          console.log(err)
        })
      },
      initData() {
        this.courseId = this.$route.params.courseId
        getAudioList(this.courseId).then(res => {
          if (res.data.data.length > 0) {
            this.audioList = res.data.data;
            //this.uploadData.audioName = res.data.data.audioName
            //this.uploadData.audioM3u8 = res.data.data.audioM3u8 != null && res.data.data.audioM3u8 != ''
          }
        }).catch(err => {
          console.log(err)
        })
      },
      deleteDatum(id,index) { // 删除上传资料
        this.$confirm('确定删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           this.loading = true;
           delAudio(id).then(res=>{
            if(res.data.statusCode == 200){
              this.loading = false;
              this.audioList.splice(index,1)
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            }else{
              this.loading = false;
              this.$message.error('删除失败');
            }
          })
          
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      handlePreview(file) {
        console.log(file);
      },
      beforeAvatarUpload(file) {
        const isMP3 = file.type == 'audio/mp3' || file.type == 'audio/mpeg'
        const maxSize = file.size / 1024 / 1024 < 100
        if (!isMP3) {
          this.$message({
            message: '音频必须为 MP3 格式',
            type: 'warning'
          })
          return false
        }
        if (!maxSize) {
          this.$message({
            message: '允许最大可上传文件大小为 100M',
            type: 'warning'
          })
          return false
        }
        this.btnLoading = true;
      },
      handleSuccess(response, file, fileList) {
        this.fileList =  [{name: file.name, url: '/dist/static/img/audio.png',keyId:response.key}]
        this.postForm.audioName = file.name
        this.postForm.qiniuObject = response.key
        this.btnLoading = false
        saveAudioDetail(this.courseId, this.postForm).then(res => {
          if (res.data.statusCode == 200) {
            // 刷新数据
            // this.uploadData.audioName = this.postForm.audioName
            // this.uploadData.audioM3u8 = false
            this.initData()
          } else {
            this.$message({
              message: '音频入库失败!',
              type: 'error'
            })
          }
        }).catch(err => {
          console.log(err)
        })
      },
      handleError(error, response, file) {
        this.$message({
              message: '上传音频失败!',
              type: 'error'
        })
        console.log(error.toString())
      },
      handleSlice(detailId) {
        this.$confirm('切片前是否确认该音频已经为ACC格式，确定切片该音频？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          audioSlice(detailId).then(res => {
            this.uploadData.audioM3u8 = true
            this.$message({
              message: '切片成功,切片过程需要2-5分钟，请耐心等待',
              type: 'info'
            })
          }).catch(err => {
            console.log(err)
          })
        }).catch(() => {

        })
      },
      close() {
        this.$store.dispatch('delVisitedViews', this.$route).then((views) => {
          const latestView = views.slice(-1)[0]
          if (latestView) {
            this.$router.push(latestView.path)
          } else {
            this.$router.push('/')
          }
        })
      }
    }
  }
</script>

<style scoped>
	p,h3 {margin:0;padding:0}
	h3{
		font-weight: 500;
		font-size: 14px;
		height: 36px;
		background: #eee;
		border-bottom: 1px solid #ddd;
		padding: 0 20px;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}
	.addBox {
		width: 100%;
		overflow: auto;
		background: #fff;
	}
	table,tr,td,th{
		border: 1px solid #ddd;
		border-collapse: collapse;
		border-spacing: 0;
		text-align: center;
	}
	th{
		background: #f5fafe;
	}
	table{
		font-size: 12px;
		color: #333;
		width: 100%;
		line-height: 36px;
		margin-bottom: 20px;
	}
	b{
    	cursor: pointer;
    	font-weight: 500;
    }
	b:hover{
		color: #0A76A4;
  }

</style>
